//
// Created by wormtql on 2020/11/24.
//

#include <map>
#include <string>
#include <cstring>
#include <fstream>
#include <queue>
#include <vector>
#include <sstream>
#include <iostream>
#include <set>
#include <cmath>
#include <algorithm>

#define INF 0x3f3f3f3f

using namespace std;

struct Edge {
    int to;
    int from;
    int next;
};

// trace
int trace_count = 0;
vector<string> traces[6000];

void parse_csv_line(char * line, vector<string> & data) {
    int state = 0;
    char buf[1000] = { 0 };
    int l = 0;

    int i = 0;
    while (line[i]) {
        if (state == 0) {
            if (line[i] == ',') {
                state = 1;
            } else {
                buf[l++] = line[i];
                i++;
            }
        } else if (state == 1) {
            buf[l] = 0;
            l = 0;
            data.push_back(string(buf));
            i++;
            state = 0;
        }
    }
    if (l != 0) {
        buf[l] = 0;
        data.emplace_back(buf);
    }
}

bool load_traces(char * filename, int limit) {
    ifstream file(filename);
    if (!file.is_open()) {
        return false;
    }

    char buf[10000];
    while(file.getline(buf, 10000) && trace_count < limit) {
        vector<string> ts;
        parse_csv_line(buf, ts);

        for (const string & s: ts) {
            traces[trace_count].push_back(s);
        }

        trace_count++;
    }

    return true;
}

int main(int argc, char * argv[]) {
#ifdef REMOTE
    printf("running remotely\n");
#endif
    if (argc < 3) {
        printf("get all functions in a trace.csv file\n\n");
        printf("app <trace.csv> <output.csv>\n\n");
        printf("trace.csv:          call trace\n");
        printf("output.csv:         distance matrix\n");
        return 0;
    }

    // load trace
    load_traces(argv[1], 10000);
    printf("traces loaded\n");
    printf("trace count: %d\n\n", trace_count);

    set<string> all_functions;
    vector<string> function_list_vec;
    for (int i = 0; i < trace_count; i++) {
        for (int j = 0; j < traces[i].size(); j++) {
            all_functions.insert(traces[i][j]);
        }
    }
    for (auto i = all_functions.begin(); i != all_functions.end(); i++) {
        function_list_vec.push_back(*i);
    }

    ofstream output(argv[2]);

    int count = function_list_vec.size();
    printf("all function count: %d\n", count);
    for (auto i = 0; i < count; i++) {
        output << function_list_vec[i] << endl;
    }

    output.close();
}